package com.yc.controller;

import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yc.biz.IMgoodsService;
import com.yc.biz.IMorderService;
//import com.yc.biz.impl.CartService;
import com.yc.config.AlipayConfig;
import com.yc.dto.Result;
import com.yc.entity.Maddress;

import com.yc.entity.Morder;
import com.yc.entity.User;
import com.yc.mapper.MorderMapper;
//import com.yc.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxw
 * @since 2024-11-10
 */
@Controller
@RequestMapping("//morder")
public class MorderController {
//    @Autowired
//    JwtUtil jwtUtil;
    @Autowired
    MorderMapper morderMapper;
//    @Autowired
//    CartService cartService;
    @Autowired
    IMorderService morderService;

    Integer getUserId(HttpServletRequest request){
        // 从HTTP请求的Cookie中获取JWT
        Cookie[] cookies = request.getCookies();
        String jwt = null;
        for (Cookie cookie : cookies) {
            if ("jwt".equals(cookie.getName())) {
                jwt = cookie.getValue();
                break;
            }
        }
        // 解析JWT并获取Claims
//        Claims claims = jwtUtil.parseJWT(jwt);
        // 从Claims中获取用户信息
//        Integer userId = claims.get("userId", Integer.class);
        return 1;
    }
    @RequestMapping("addOrder")
    Result addOrder(@RequestBody List<Integer> ProductsId,
                    @RequestParam int aid, @RequestParam
                 int quantity, @RequestParam int gprice, @RequestParam Long totalprice, @RequestParam String remark,
                    HttpServletRequest request){
        int uid=this.getUserId(request);

        List<Morder> list=new ArrayList<>();

        Morder order=new Morder();
        for (Integer goodId:ProductsId){
            LocalDateTime currentDateTime = LocalDateTime.now();
            order.setCreatetime(currentDateTime);
            order.setAid(aid);
            order.setUid(uid);
            order.setGid(goodId);
            order.setQuantity(quantity);

            order.setTotalprice(BigDecimal.valueOf(totalprice));
            order.setRemark(remark);
            order.setStatus(0);
            morderMapper.insert(order);
//            cartService.removeFromCart(uid,goodId);//去除购物车的商品，当订单生产后
            LambdaUpdateWrapper<Morder> lqw = new LambdaUpdateWrapper<>();
            lqw.eq(Morder::getUid, uid);
            lqw.eq(Morder::getGid,goodId);
            lqw.eq(Morder::getCreatetime,currentDateTime);
            Morder morder=morderMapper.selectOne(lqw);
            list.add(morder);
        }
        return Result.ok("订单添加成功",list);
    }

    @RequestMapping("gayorder")
    public String order (User user, String oid) {
        //根据传递过来的订单编号拿到订单对象
        Morder order = morderMapper.selectById(oid);
        AlipayConfig alipayConfig = new AlipayConfig();
        String body= alipayConfig.goAlipay(order);//表单内容
        return body;
    }

    @RequestMapping("/payDone")
    @ResponseBody
    //@RequestParam没有这个注解就无法正确的接受参数
    public String payDone(@RequestParam Map<String, String> ms) throws Exception {
        //验签【不然的话就可以在地址栏上手动传递参数】
        Boolean f = Factory.Payment.Common().verifyNotify(ms);
        //如果验证不通过，那就抛出一个异常
        if(!f){
//            throw new BusinessException("Unknown error occurred during payment processing.");
        }
        String oid = ms.get("oid");//拿到请求中的订单编号

        // 假设 morderMapper 是 MyBatis-Plus 的 Mapper 接口
        UpdateWrapper<Morder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("oid", oid) // 设置条件
                .set("status", 1) // 设置要更新的字段
                .set("pay_date", new Date()); // 设置支付时间
        morderMapper.update(null, updateWrapper); // 第一个参数是实体对象（这里不需要，所以传 null），第二个参数是 UpdateWrapper



//        morderMapper.update(new UpdateWrapper<Morder>()
//                //根据订单编号，修改订单状态【未支付=>已支付】
//                .eq("oid", oid)
//                .set("status", 1)
//                .set("paydatetime", new Date())//设置支付的时间
//        );
        return "<script>\n" +
                "    alert('支付成功')\n" +
                "    location.href = '/'\n" +
                "</script>";
    }


    @RabbitListener(queuesToDeclare=@Queue("promotionQueue"))
    public void addPromotionOrder(Morder morder){
        try{
            morderService.createPromotionOrder(morder);

        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
